package com.example.demo.app.controller;

import java.util.List;
import java.util.function.Consumer;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.app.model.User;
import com.example.demo.app.validate.UserValidate;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableListMultimap.Builder;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Controller
public class UserController {
	
	@GetMapping("/userInfo")
	public ModelAndView userInfo() {
		ModelAndView userView = new ModelAndView("user");
		return userView;
	}

	
	@PostMapping("/addUser")
	public String addBook(@Validated User user,BindingResult result, Model model) {
		log.info("addUser:{}",user);
		if(result.hasErrors()){
			List<ObjectError> allErrors = result.getAllErrors();
			Builder<String, String> builder = ImmutableListMultimap.builder();
			allErrors.stream().forEach(new Consumer<ObjectError>() {

				@Override
				public void accept(ObjectError t) {
					builder.put(t.getObjectName(), t.getDefaultMessage());
				}
			});
			
			ImmutableListMultimap<String, String> build = builder.build();
			model.addAttribute("result",build.values());
		}else {
			model.addAttribute("result","success");
		}
		return "user";
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setValidator(new UserValidate());
	}
	
}
